//
//  FansOrderList.swift
//  LeGou
//
//  Created by lxm on 2022/9/4.
//

import UIKit

class FansOrderList : ZMViewController, UITableViewDelegate, UITableViewDataSource, ListRequestObjct {
    //MARK: --------------------属性--------------------
    var listData = [MineModels.ProfitList]()
    var page = 1
    var pageSize = 10
    var refreshScrollView : UIScrollView {
        tableView
    }
    
    // 状态（0已付款、1已结算、2已失效）
    var type = -1
    
    //MARK: --------------------UI控件--------------------
    let tableView = UITableView().then { t in
        t.separatorStyle = .none
        t.tableFooterView = UIView()
    }
    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        tableView.mj_header?.beginRefreshing()
    }
    
    //MARK: --------------------UI--------------------
    func setUI() {
        title = ""
        setUpTableView()
        view.backgroundColor = "#F5F5F5".zm.hex()

    }
    
    func setUpTableView() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = "#F5F5F5".zm.hex()
        tableView.zm.register(nibName: "PorfitListCell", reuserId: "PorfitListCell")
        
        view.addSubview(tableView)
        addRefresh(scrollView: tableView) { [weak self] refresh in
            guard let self = self else {return}
            if refresh {
                self.page = 1
            }
            self.loadList()
        }
        addNodataScrollView(scrollView: tableView)
        emptyTitle = "暂无数据"
        emptyImg = "nodata"
    }
    
    func addConstraints() {
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        ZMPayManager.shard.payCallBack.subscribe(onNext:{ [unowned self] resp in
            switch resp {
            case .success:
                self.tableView.mj_header?.beginRefreshing()
            default:
                ZMToast.showToast(title: resp.rawValue)
            }
        }).disposed(by: disposeBag)
        
        ZMNotification.shard.subject.subscribe(onNext:{ [unowned self] resp in
            switch resp {
            case .refreshOrderList:
                self.tableView.mj_header?.beginRefreshing()
            default:break
            }
        }).disposed(by: disposeBag)
    }
    
    func loadList() {
        var pa = ["limit" : pageSize, "page" : page]
        if type != -1 {
            pa["status"] = type
        }
        
        ZMUtil.listRequest(type: MineModels.ProfitList.self, api: MineAPI.fansOrders(pa)) { resp in
            self.listRequest(resp)
        }
    }

    
    //MARK: --------------------delegate--------------------
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.mj_footer?.isHidden = listData.count == 0
        return listData.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PorfitListCell") as! PorfitListCell
        let data = listData[indexPath.row]
        cell.tbIcon.isHidden = true
        cell.partnerIcon.isHidden = data.type == 0
        if data.orderType == .phoneCharge {
            cell.img.image = UIImage.init(named: "tele_record")
        } else {
            cell.img.zm.setImage(urlStr: data.image)
        }
        cell.name.text = data.orderTitle
        cell.orderNo.text = data.orderCreateTime
        if data.status == .payed {
            cell.state.text = "已付款"
            cell.state.textColor = "#333333".zm.hex()
            cell.tips.text = "订单号：\(data.orderId)"
        } else if data.status == .invalid {
            cell.state.text = "已失效"
            cell.state.textColor = "#999999".zm.hex()
            cell.tips.text = "订单号：\(data.orderId)"
        } else if data.status == .over {
            cell.state.text = "已结算"
            cell.state.textColor = "#999999".zm.hex()
            let text = "结算时间：\(data.settleTime)\n".zm.attributedStr(attrs: [.foregroundColor : "#333333".zm.hex(), .font : UIFont.systemFont(ofSize: 14, weight: .regular)]).zm.append(str: "订单号：\(data.orderId)", attri: ["c" : "#666666", "f" : "12"])
            let pa = NSMutableParagraphStyle()
            pa.lineSpacing = 8
            text.addAttributes([.paragraphStyle : pa], range: NSRange(location: 0, length: text.length))
            cell.tips.attributedText = text
        }
        cell.refundMoney.text = "\(data.income.zm.toString(keep: 2))元"
        cell.setStyle(s: data.status == .invalid ? 1 : 0)
        return cell
    }
    
}
